<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>键盘事件</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        body{
            height: 100vh; 
            display:flex;
            justify-content: center;
            align-items: center;
        }
        .box{
            width: 150px;
            height: 150px;
            border:solid 1px #ddd;
        }
    </style>
</head>
<body>
    <div id="root"></div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        class App extends React.Component{
            state = {
                left: 0,
                top: 0
            }

            render(){
                let {left, top} = this.state;
                return <div className="box" style={{transform: `translateX(${left}px) translateY(${top}px)`}}></div>
            }

            //生命周期回调, 组件挂载完毕后, 自动执行
            componentDidMount(){
                //绑定事件为 body 绑定事件
                document.body.onkeydown = (e) => {
                    if(e.keyCode === 37){
                        //向左
                        this.setState({
                            left: this.state.left - 10
                        })
                    }else if(e.keyCode === 39){
                        //向右
                        this.setState({
                            left: this.state.left + 10
                        })
                    }
                }
            }
        }

        ReactDOM.render(<App />, document.querySelector("#root"));
    </script>
</body>
</html>